package com.dynamic.model.util.common;

import com.dynamic.model.util.redis.CacheManager;
import com.qiniu.util.Auth;

import net.sf.json.JSONObject;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;

public class FileUploadUtil {
	private static final Logger LOGGER = Logger.getLogger(FileUploadUtil.class);
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	static String ACCESS_KEY = (String) CacheManager.getInstance().getAttributeObj("qiniu.ACCESS_KEY");
	static String SECRET_KEY = (String) CacheManager.getInstance().getAttributeObj("qiniu.SECRET_KEY");
	// 要上传的空间
	static String bucketname = (String) CacheManager.getInstance().getAttributeObj("qiniu.bucketname");

	// 密钥配置
	static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	// 创建上传对象
	static UploadManager uploadManager = new UploadManager();

	private static class NestClass {
		private static FileUploadUtil instance;
		static {
			instance = new FileUploadUtil();
		}
	}

	// 不能直接new
	private FileUploadUtil() {
		LOGGER.info("实例化");
	}

	public static FileUploadUtil getInstance() {
		return NestClass.instance;
	}

	public String  upload(String fileName, String FilePath) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(FilePath, fileName, auth.uploadToken(bucketname));
			// 打印返回的信息
			LOGGER.info(res.bodyString());
			JSONObject json=JsonUtil.toJSONObject(res.bodyString());
			return json.getString("key");
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			LOGGER.info(r.toString());
			try {
				// 响应的文本信息
				LOGGER.info(r.bodyString());
				return null;
			} catch (QiniuException e1) {
				return null;
			}
		}
	}

	public String coverUpload(String fileName, String FilePath) throws IOException {
		try {
			// 调用put方法上传，这里指定的key和上传策略中的key要一致
			Response res = uploadManager.put(FilePath, fileName, auth.uploadToken(bucketname, fileName));
			// 打印返回的信息
			/*LOGGER.info(res.bodyString());*/
			JSONObject json=JsonUtil.toJSONObject(res.bodyString());
			return json.getString("key");
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常信息
			LOGGER.info(r.toString());
			try {
				// 响应的文本信息
				LOGGER.info(r.bodyString());
				return null;
			} catch (QiniuException e1) {
				return null;
			}
		}
	}
}
